"""
file: productPage.py
Author: 城下秋草
Desc: 
"""
from playwright.sync_api import Page

from pom.pages.basePage import BasePage
from pom.util.custom_exception import ElementNotFound
from pom.util.logger import logger


class ProductPage(BasePage):
    def __init__(self, page: Page):
        super().__init__(page)
        self.page = page
        self.title = self.get_element("title","test-id")

    @property
    def has_correct_title(self):
        if self.title.text_content() == "Products":
            return True
        else:
            return False

    def add_product(self,name:str):
        if self.product_in_cart(name) :
            logger.warning(f"商品{name}已经在购物车！")
            return
        prod_id = f"add-to-cart-{name.lower().replace(" ","-")}"
        add_btn = self.get_element(prod_id,"test-id")
        try:
            add_btn.click()
            logger.info(f"添加了商品:{name}")
        except Exception as e:
            raise ElementNotFound(prod_id)


    def get_badge_number(self):
        ele_badge = self.get_element("shopping-cart-badge","test-id")
        if ele_badge.is_visible():
            number = int(ele_badge.text_content())
            logger.info(f"当前购物车商品数量:{number}")
            return number
        else:
            return 0

    def product_in_cart(self,name:str):
        remove_id = f"remove-{name.lower().replace(" ","-")}"
        remove_btn = self.get_element(remove_id,"test-id")
        if remove_btn.is_visible():
            return True
        else:
            return False

    def goto_checkout(self):
        ele_cart_link = self.get_element("shopping-cart-link","test-id")
        try:
            ele_cart_link.click()
        except Exception as e:
            raise ElementNotFound("购物车链接")